package com.qyhl.webtv.module_user.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.user.UserBean;
import com.qyhl.webtv.commonlib.entity.user.UserInfoBean;
import com.qyhl.webtv.commonlib.entity.user.json.JsonUser;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.config.AppConfigUtil;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.push.PushTools;
import com.qyhl.webtv.module_user.common.UserUrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

import okhttp3.Response;

/**
 * Created by qyhl on 2017/11/22.
 */

public class LoginUtils {

    private static Response response = null;

    private static ArrayBlockingQueue<Map<String, Object>> loginQueue = new ArrayBlockingQueue<>(5);
    private static boolean checking = true;

    /**
     * 验证token是否有效
     *
     * @param context
     * @return
     */
    public static void isTokenValid(final Context context, TokenValidCallBack callBack) {
        String loginToken = (String) AppConfigUtil.getInstance().getConValue(AppConfigConstant.LOGIN_TOKEN);
        JsonUser bean = null;
        EasyHttp.get(UserUrl.GET_COMPARE_TOKEN)
                .params("token", loginToken)
                .syncRequest(true)
                .execute(new SimpleCallBack<UserBean>() {
                    @Override
                    public void onError(ApiException e) {
                        PushTools.unBindAccount();
                        callBack.error();
                    }

                    @Override
                    public void onSuccess(UserBean s) {
                        callBack.success();
                    }
                });


    }


    /**
     * 注册登录信息返回提示
     *
     * @param code
     * @return
     */
    public static String getMessage(int code) {
        String message = null;
        switch (code) {
            case 201:

                message = "参数异常！";
                break;
            case 206:
                message = "系统发送短信验证码出错！";
                break;
            case 207:
                message = "对不起,今日验证码发送次数已超过系统最大限制！";
                break;
            case 208:
                message = "验证码已经失效,请重新获取验证码！";
                break;
            case 210:
                message = "该手机号已经被注册！";
                break;
            case 212:
                message = "密码错误！";
                break;
            case 211:
                message = "该账号未注册";
                break;
            case 213:
                message = "您的登录已失效！";
                break;
            case 214:
                message = "该昵称已被注册！";
                break;
            case 215:
                message = "邀请码不存在！";
                break;
            case 216:
                message = "昵称包含敏感字！";
                break;
            case 209:

            case 202:

            case 205:
                message = "验证码错误";
                break;
            default:
                message = "未知错误！";
                break;

        }
        return message;
    }

    /**
     * 圈子
     *
     * @param code
     * @return
     */
    public static String getCircleMessage(int code) {
        String msg = "";
        switch (code) {
            case 200:
                break;
            case 1://请求失败
                msg = "请求失败，请稍后再试！";
                break;
            case 11://没有时间戳
                msg = "请求失败，请稍后再试！";
                break;
            case 12://请求超时
                msg = "请求超时，请稍后再试！";
                break;
            case 13://加密错误
                msg = "请求失败，请稍后再试！";
                break;
            case 99://文字包含敏感字
                msg = "文字包含敏感字或无意义内容！";
                break;
            case 101://已关注，无法重复关注
                msg = "已关注，无法重复关注";
                break;
            case 102://未关注，无法取消关注
                msg = "未关注，无法取消关注";
                break;
            case 103://已屏蔽，无法再次屏蔽
                msg = "已屏蔽，无法再次屏蔽";
                break;
            case 104://未屏蔽，无法取消屏蔽
                msg = "未屏蔽，无法取消屏蔽";
                break;
            case 111://已喜欢，无法再次喜欢
                msg = "已喜欢，无法再次喜欢";
                break;
            case 112://未喜欢，无法取消喜欢
                msg = "未喜欢，无法取消喜欢";
                break;
            case 113://主题不存在
                msg = "该主题不存在！";
                break;
            case 121://评论不存在
                msg = "该评论不存在！";
                break;
            case 131://无效的主题类型
                msg = "无效的主题类型";
                break;
            case 132://标签无效
                msg = "标签无效";
                break;
            case 133://站点不存在
                msg = "站点不存在";
                break;
            case 141://内容过少
                msg = "内容过少";
                break;
            case 151://对方已拉黑你
                msg = "对方已拉黑你";
                break;
            case 155://您被禁言了
                msg = "您被禁言了";
                break;
            case 161://无效的举报
                msg = "无效的举报";
                break;
            case 171://无法删除
                msg = "无法删除";
                break;
            default:
                msg = "请求失败，请稍后再试！";
                break;
        }
        return msg;
    }

    /**
     * 积分错误码
     *
     * @param code 错误码
     * @return 错误信息
     */
    public static String getScoreMessage(int code) {
        switch (code) {
            case 1:
                return "请求出错！";
            case 2:
                return "code:2,请求出错！";
            case 3:
                return "请求失败，参数异常！";
            case 4:
                return "请求失败，地址不存在！";
            case 5:
                return "code:5,请求出错！";
            case 11:
                return "操作异常！";
            case 12:
                return "今天已经签到！";
            case 13:
                return "金币达到上限！";
            case 14:
                return "行为不存在！";
            case 15:
                return "用户不存在！";
            case 21:
                return "金币不足！";
            case 22:
                return "金币太少！";
            case 31:
                return "未绑定支付宝账号！";
            case 32:
                return "未绑定微信账号！";
            case 33:
                return "提现余额不足！";
            case 34:
                return "提现手续费不足！";
            case 35:
                return "提现金额不在范围内！";
            case 36:
                return "未知的支付平台！";
            default:
                return "请求出错！";
        }
    }

    /**
     * 用户登陆成功设置用户信息
     *
     * @param bean
     * @param tag
     */
    public static void setloginSuccess(UserInfoBean bean, String tag) {
        ActionLogUtils.getInstance().onEvent(tag);
        AppConfigUtil config = AppConfigUtil.getInstance();
        if (StringUtils.isEmpty(bean.getNickName())) {
            config.setConValue(AppConfigConstant.NICK_NAME, bean.getUsername().replace(bean.getUsername().substring(3, 7), "****"));
        } else {
            config.setConValue(AppConfigConstant.NICK_NAME, bean.getNickName());
        }
        config.setConValue(AppConfigConstant.USER_NAME, bean.getUsername());
        config.setConValue(AppConfigConstant.HEAD_ICON, bean.getLogo());
        config.setConValue(AppConfigConstant.EMAIL, bean.getEmail());
        config.setConValue(AppConfigConstant.CODE, bean.getCode());
        config.setConValue(AppConfigConstant.INVITE_CODE, bean.getInviteCode());
        config.setConValue(AppConfigConstant.PHONE_NUM, bean.getTelphone());
        config.setConValue(AppConfigConstant.USER_CHECK,bean.getChecked());
        config.setConValue(AppConfigConstant.USER_CHECK_REASON,bean.getFailReason());
        String sex;
        if (StringUtils.isEmpty(bean.getSex())) {
            sex = "C";
        } else {
            sex = bean.getSex();
        }

        //四川融媒统计
        if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
            StatisticsMainInit.appLogin(bean.getUsername());
        }
        config.setConValue(AppConfigConstant.SEX, sex);
        Hawk.put("login", bean);
        BusFactory.getBus().postSticky(new Event.LoginMessage(true));
        //绑定推送用户账号
        PushTools.BindAccount(bean.getTelphone());
        //绑定用户已关注的图文直播
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                ArrayList<Integer> data = Hawk.get("scene_list");
                if (data != null) {
                    for (int i = 0; i < data.size(); i++) {
//                        PushTools.unBindTagByDevice("Scene_" + ChannelConfig.SITE_ID + "_" + data.get(i));
//                        PushTools.BindTag("Scene_" + ChannelConfig.SITE_ID + "_" + data.get(i));
                        String userName = (String) config.getConValue(AppConfigConstant.USER_NAME);
                        ;

                        //开启提醒 GET_TELETEXT_FOLLOW attention/remind
                        //TODO 请求网络开启提醒
                    }
                }
                Hawk.delete("scene_list");
//                PushTools.getAttentionList(MyConfig.userName);
            }
        }, 2000);
    }


    public static void checkLogin(LoginCallBack loginCallBack) {
        if (loginQueue.size() < 5) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("l", loginCallBack);
            loginQueue.offer(map);
            if (checking) {
                checking = false;
                String loginToken = (String) AppConfigUtil.getInstance().getConValue(AppConfigConstant.LOGIN_TOKEN);
                EasyHttp.get(UserUrl.GET_COMPARE_TOKEN)
                        .params("token", loginToken)
                        .execute(new SimpleCallBack<String>() {
                            @Override
                            public void onError(ApiException e) {
                                loginError("网络异常 " + e.toString());
                                checking = true;
                            }

                            @Override
                            public void onSuccess(String s) {
                                loginSuccess(new Gson().fromJson(s, JsonUser.class));
                                checking = true;
                            }
                        });
            }
        } else {
            loginCallBack.error("卡住了...");
        }
    }

    private static void loginError(String s) {
        while (!loginQueue.isEmpty()) {
            Map<String, Object> poll = loginQueue.poll();
            ((LoginCallBack) poll.get("l")).error(s);
        }
    }

    private static void loginSuccess(JsonUser bean) {
        while (!loginQueue.isEmpty()) {
            Map<String, Object> poll = loginQueue.poll();
            LoginCallBack loginCallBack = (LoginCallBack) poll.get("l");
            if (bean != null && bean.getCode() == 200) {
                //已登陆
                loginCallBack.login(true);
            } else {
                //未登陆
                loginCallBack.login(false);
                //解绑推送账号
                PushTools.unBindAccount();
            }
        }
    }


    public interface LoginCallBack {
        void login(boolean isLogin);

        void error(String s);
    }

    public interface TokenValidCallBack {
        void success();

        void error();
    }

}
